
/**
 * action 创建函数 - 用户模块
 */

'user strict';

import * as types from './actionTypes';
import {cartView} from './cartActions';
import Util from '../common/utils';
import * as urls from '../common/constants_url';
import * as Storage from '../common/Storage';
import { Alert } from 'react-native';
import {Toast} from 'teaset';
import {alipay} from '../actions/alipayActions';
import Common from '../common/constants';
import DeviceInfo from 'react-native-device-info';


export let userFromSync = (user) => {
    return (dispatch) => {
        // console.log('userFromSync',user);
        dispatch({type: types.kUserFromSync, user: user});
    }
};



/**
手机号，图片识别码，手机信息
*/
export let smsVerifyCode = (thiz,mobile, characterCode) => {
    let url = urls.smsVerifyCode;
    // url='http://www.xianchuang123.com/index.php?m=Home&c=User&a=appsend_sms_reg_code&mobile='+mobile+'&pmobile='+pmobile;
    let device=Util.getDeviceInfo();

    let data = {
        mobile: mobile,
        code: characterCode,
        device:JSON.stringify(device)
    };

    return (dispatch) => {
        dispatch({type: types.kSmsVerifyCode});
        Util.post(url, data,
            (status, code, message, data, share) => {

                if(status){
                    Toast.smile('您的验证码\n已发出!')
                }else{
                    thiz.timeHit=60;//跳过时间
                    Toast.fail(message)
                }
            },
            (error) => {
                dispatch({'type': types.kActionError});
            });
    }
};


export let userRegister = (thiz,mobile, password, password2, code,pmobile,nickname) => {
    let url = urls.register;
    // url='http://xapi.tancb.com/index.php/Home/AppUser/appreg'+'/mobile/'+mobile+'/password/'+password+'/password2/'+password2+'/code/'+code+'/pmobile/'+pmobile;
          //http://www.xianchuang123.com/index.php/Home/User/appreg/mobile/18127816781/password/123456/password2/123456/pmobile/13710168515/code/8178
    let data = {
        mobile: mobile,
        password: password,
        password2:password2,
        code: code,
        pmobile:pmobile,
        nickname:nickname,
    };


        let tmpUrl=url;
    for (var xx in data) {if(data[xx]!=undefined&&data[xx]!='')tmpUrl+='/'+xx+'/'+data[xx];}
    console.log('tmpUrl:'+tmpUrl);

    return (dispatch) => {
        // thiz.setState({isloading:true});
        dispatch({type: types.kUserRegister});
        Util.post(url, data,
            (status, code, message, data, share) => {
                let user = {};
                console.log('data:'+JSON.stringify(data));

                // thiz.setState({isloading:false});
                if (status) 
                {
                    user = data.user;
                    Storage.setUser(user);
                    // thiz.props.navigator.popToTop();
                    // dispatch({type:types.kUserLoginReceived, status:status, code:code, message:message, share:share, user:user});
                    // console.log("login:"+mobile+","+password);
                    // dispatch(userLogin(mobile, password));
                }else{
                    Toast.message(message);

                }
                dispatch({type:types.kUserRegisterReceived, status:status, code:code, message:message, user:user, share:share});



                
                
            },
            (error) => {
                console.log('error:',error);
                dispatch({'type': types.kActionError});
                dispatch({type:types.kUserRegisterReceived});
            });
    }
};

export let userView = () => {
    let url = 'http://local.eleteamapi.ygcr8.com/v1/user/view?id=2';
    return (dispatch) => {
        dispatch({'type':types.kUserView});
        Util.get(url,
            () => {},
            () => {});
    }
};




// export let userLogin = (mobile, password) => {
//     let url = urls.login;

//     let data = {
//         mobile: mobile,
//         password: password
//     };
//     return (dispatch) => {
//         dispatch({'type': types.kUserLogin});
//         Util.post(url, data,
//             (status, code, message, data, share) => {
//                 console.log('data['+url+']:'+data);
//                 let app_cart_cookie_id = '';
//                 let user = {};
//                 if (status) {
//                     user = data.user;
//                     console.log('user:'+user);
//                     console.log('app_cart_cookie_id:'+app_cart_cookie_id);
//                     app_cart_cookie_id = data.app_cart_cookie_id;
//                     Storage.setAppCartCookieId(app_cart_cookie_id);
//                     Storage.setUser(user);
//                 }

                
//                 dispatch({type:types.kUserLoginReceived, status:status, code:code, message:message, share:share, user:user, app_cart_cookie_id:app_cart_cookie_id});
//                 dispatch(cartView(app_cart_cookie_id, user.access_token));
//             },
//             (error) => {
//                 Alert.alert(error.message);
//                 dispatch({'type': types.kActionError});
//             });
//     }
// };



export let userLogin = (mobile, password) => {
    let url = urls.login;
        // url='http://xapi.tancb.com/index.php/Home/AppUser/app_login';

    let data = {
        mobile: mobile,
        password: password
    };
    // console.log('name:'+mobile+" password:"+password);
    return (dispatch) => {
        dispatch({'type': types.kUserLogin});
        Util.post(url, data,
            (status, code, message, data, share) => {
                console.log('userLogindata['+url+']:'+status,data);
                let app_cart_cookie_id = '';
                let user = {};
                if (status) {
                    user = data.user;
                    console.log('user===>:',user);
                    console.log('app_cart_cookie_id:'+app_cart_cookie_id);
                    app_cart_cookie_id = data.app_cart_cookie_id?data.app_cart_cookie_id:'';
                    Storage.setAppCartCookieId(app_cart_cookie_id);
                    Storage.setUser(user);
                }

                
                dispatch({type:types.kUserLoginReceived, status:status, code:code, message:message, share:share, user:user, app_cart_cookie_id:app_cart_cookie_id});
                // dispatch(cartView(app_cart_cookie_id, user.access_token));
            },
            (error) => {
                Toast.message(error.message);
                dispatch({'type': types.kActionError});
            });
    }
};

export let userLogout = (access_token,extra) => {
    console.log('tuichu');
    let url = urls.logout;
    let data={access_token:access_token,extra:JSON.stringify(extra)};
    return (dispatch) => {
        dispatch({'type': types.kUserLogout});
        console.log('tuichu2:'+url);
        Util.post(url,data,
            (status, code, message, data, share) => {
                // let app_cart_cookie_id = '';
                if (status) {
                    // app_cart_cookie_id = data.app_cart_cookie_id;
                    // Storage.setAppCartCookieId(app_cart_cookie_id);//后台需要保存这个账号和密码
                    Storage.setUser({});
                }
                dispatch({type:types.kUserLogoutReceived, status:status, code:code, message:message, share:share, user:{}});
                // dispatch(cartView(app_cart_cookie_id, ''));
            },
            (error) => {
                console.log('error',error);
                Toast.message(error.message);
                dispatch({'type': types.kActionError});
            });
    }
};


export let haoyouList = (access_token) => {
    let url = urls.kUrlUserHaoyou;
    let data = {
        access_token: access_token
    };
    return (dispatch) => {
        dispatch({type: types.kUserHaoyouList});
        Util.post(url, data,
            (status, code, message, data, share) => {
                let summary ={};
                let haoyouList = [];
                if (status) {
                    haoyouList = data.haoyouList;
                    summary = data.summary;
                    console.log('summary:'+summary);
                }

                dispatch({type:types.kUserHaoyouListReceived, status:status, code:code, message:message, share:share, 
                    haoyouList:haoyouList, summary:summary});
            },
            (error) => {
                console.log('Fetch ['+url+']kActionError message: ' + error);
                dispatch({'type': types.kActionError});
            });
    }
};


export let qianbao = (access_token) => {
    let url = urls.kUrlUserQianbao;
    let data = {
        access_token: access_token
    };
    return (dispatch) => {
        dispatch({type: types.kUserQianbao});
        Util.post(url, data,
            (status, code, message, data, share) => {
                let qianbao = {};
                if (status) {qianbao = data.qianbao;}
                // console.log('Fetch haoyouList message: ' + data.qianbao);
                dispatch({type:types.kUserQianbaoReceived, status:status, code:code, message:message, share:share, qianbao:qianbao});
            },
            (error) => {
                console.log('Fetch ['+url+']kActionError message: ' + error);
                dispatch({'type': types.kActionError});
            });
    }
};

export let qianbaoList = (access_token) => {
    let url = urls.kUrlUserQianbaoList;
    let data = {
        access_token: access_token
    };
    return (dispatch) => {
        dispatch({type: types.kUserQianbaoList});
        Util.post(url, data,
            (status, code, message, data, share) => {
                let qianbaoList = [];
                if (status) {qianbaoList = data.qianbaoList;}
                // console.log('Fetch haoyouList message: ' + data.qianbaoList);
                dispatch({type:types.kUserQianbaoListReceived, status:status, code:code, message:message, share:share, qianbaoList:qianbaoList});
            },
            (error) => {
                console.log('Fetch ['+url+']kActionError message: ' + error);
                dispatch({'type': types.kActionError});
            });
    }
};


// 请求热搜关键词
//subItem:{id,code,name,parent_id,ico,article_id}
export let subItemsByParentId = (level_type,parent_id)=> {
    let url = urls.kUrlSubItemsByParentId +'?type='+ level_type +'?parent_id='+ parent_id;
    return (dispatch) => {
        dispatch({'type': types.kSubItemsByParentId});
        Util.get(url,
            (status, code, message, data, share) => {
                let subItems =[];
                if (status) {
                    subItems = data.subItems;                   
                }
                dispatch({type:types.kSubItemsByParentIdReceived, status:status, code:code, message:message, share:share, subItems:subItems,level_type:level_type});
            },
            (error) => {
                Toast.message(error.message);
                dispatch({'type': types.kActionError});
            });
    }
};


// 请求热搜关键词
//subItem:{id,code,name,parent_id,ico,article_id}
export let subItemsByParentId2 = (level_type,parent_id)=> {
    let url = urls.kUrlSubItemsByParentId +'?type='+ level_type +'?parent_id='+ parent_id;
    return (dispatch) => {
        dispatch({'type': types.kSubItemsByParentId2});
        Util.get(url,
            (status, code, message, data, share) => {
                let subItems =[];
                if (status) {
                    subItems = data.subItems;                   
                }
                dispatch({type:types.kSubItemsByParentId2Received, status:status, code:code, message:message, share:share, subItems2:subItems2,level_type:level_type});
            },
            (error) => {
                Toast.message(error.message);
                dispatch({'type': types.kActionError});
            });
    }
};




// 修改文章标题编号
export let selectedDistrict = (article_id) => {
    return (dispatch) => {
        dispatch({type: types.kSelectedDistrict, article_id: article_id});
    }
};





// 请求表单项参考
export let getFormItemList = (access_token,action_name)=> {
    let url = urls.kUrlFormItemList;
    let data = {
        access_token: access_token,
        action_name: action_name
    };
    return (dispatch) => {
        dispatch({'type': types.kFormItemList});
        Util.post(url, data,
            (status, code, message, data, share) => {
                console.log('data :' + JSON.stringify(data));

                let formItemList = [];
                let formRemarkList = [];
                let formTitle='';
                let formButtomName='';
                let formSubmitAction='';
                if (status) {
                    formItemList = data.formItemList;//表单项目
                    formTitle=data.formTitle;
                    formButtomName=data.formButtomName;
                    formSubmitAction=data.formSubmitAction;//提交表单时候的action名称
                    formRemarkList=data.formRemarkList;//表单备注
                }
                dispatch({type:types.kFormItemListReceived, status:status, code:code, message:message, share:share, 
                    formItemList:formItemList,
                    formTitle:formTitle,
                    formButtomName:formButtomName,
                    formSubmitAction:formSubmitAction,
                    formRemarkList:formRemarkList
                });
            },
            (error) => {
                Toast.show(error, {position:Toast.positions.CENTER});
                dispatch({'type': types.kActionError});
            });
    }
};

// 请求表单项参考
export let submitFormItemList = (access_token,action_name,form_item_list)=> {
    let url = urls.kUrlSubmitFormItemList;
    let data = {
        access_token: access_token,
        action_name: action_name,
        form_item_list:JSON.stringify(form_item_list)
    };
    return (dispatch) => {
        dispatch({'type': types.kSubmitFormItemList});
        Util.post(url, data,
            (status, code, message, data, share) => {
                // console.log('data :' + JSON.stringify(data));

                let submit_id = '';
                let submit_result = '';
                let submit_state = '';
                let withdrawList = [];

                if (status) {
                    log_id = data.log_id;
                    submit_result = data.submit_result;
                    submit_state = data.submit_state;
                    withdrawList = data.withdrawList;
                    Toast.show(submit_result, {position:Toast.positions.CENTER});

                }
                dispatch({type:types.kSubmitFormItemListReceived, status:status, code:code, message:message, share:share, 
                    log_id:log_id,submit_state:submit_state,submit_result:data.submit_result,withdrawList:data.withdrawList});
            },
            (error) => {
                console.log('Fetch ['+url+']kActionError message: ' + error);
                dispatch({'type': types.kActionError});
            });
    }
};


// 请求表单项参考
export let listWithdraw = (access_token)=> {
    let url = urls.kUrlWithdrawList;
    let data = {
        access_token: access_token
    };
    return (dispatch) => {
        dispatch({'type': types.kWithdrawList});
        Util.post(url, data,
            (status, code, message, data, share) => {
                console.log('data :' + JSON.stringify(data));

                let withdrawList = [];
                if (status) {
                    withdrawList = data.withdrawList;
                }
                dispatch({type:types.kWithdrawListReceived, status:status, code:code, message:message, share:share, 
                    withdrawList:withdrawList});
            },
            (error) => {
                console.log('Fetch ['+url+']kActionError message: ' + error);
                dispatch({'type': types.kActionError});
            });
    }
};


// 请求表单项参考
export let listChexianRates = (access_token)=> {
    let url = urls.kUrlListChexianRates;
    let data = {
        access_token: access_token
    };
    return (dispatch) => {
        dispatch({'type': types.kListChexianRates});
        Util.post(url, data,
            (status, code, message, data, share) => {
                console.log('data :' + JSON.stringify(data));

                let chexianRateList = [];
                if (status) {
                    chexianRateList = data.chexianRateList;
                    // Toast.show(JSON.stringify(data), {position:Toast.positions.CENTER});
                }
                dispatch({type:types.kListChexianRatesReceived, status:status, code:code, message:message, share:share, 
                    chexianRateList:chexianRateList});
            },
            (error) => {
                console.log('Fetch ['+url+']kActionError message: ' + error);
                dispatch({'type': types.kActionError});
            });
    }
};







// 请求表单项参考
export let setDomTree = (dom)=> 
{
    return (dispatch) => {
        dispatch({'type': types.kSetDomTreeReceived,dom:dom});
    }
};




//返回的对象需要包含数据：
// data:{dom:[],mchId:'',pageName:'',access_token:''}
// 请求表单项参考
export let getDomTree = (mchId,pageName,access_token,page,newestId,lastId,more)=> {
    let url = urls.kUrlGetDomTree;
    let data = {
        mchId:mchId,
        pageName:pageName,
        access_token: access_token,
        width:Common.window.width,
        height:Common.window.height,
        newestId:newestId,
        page:page,
        lastId:lastId,
        more:more,
    };
    return (dispatch) => {
        dispatch({'type': types.kSetDomTree});
        Util.post(url, data,
            (status, code, message, data, share) => {

                // console.log('data post :' + JSON.stringify(data));
                let dom = [];
                let newestId = '';
                let lastId = '';
                let more = '';
                if (status) {
                    for (var i = data.dom.length - 1; i >= 0; i--) {
                        dom.push(data.dom[i]);
                    }
                    dom = data.dom;

                     if(data.newestId!=undefined)
                     {
                        newestId=data.newestId;
                        Storage.setNewstLastId('newest',mchId,data.pageName,data.access_token,data.newestId);
                     }
                     if(data.lastId!=undefined){
                        lastId=data.lastId;
                        Storage.setNewstLastId('last',mchId,data.pageName,data.access_token,data.lastId);
                     }
                     if(data.more!=undefined){
                        more=data.more;
                     }
                }
                dispatchObject={};
                dispatchObject.status=status;
                dispatchObject.code=code;
                dispatchObject.message=message;
                dispatchObject.share=share;
                dispatchObject.newestId=newestId;
                dispatchObject.lastId=lastId;
                dispatchObject.more=more;
                dispatchObject.dom=dom;
                // console.log('dispatchObject:'+JSON.stringify(dispatchObject));      
                if(more=='header')
                {
                    dispatchObject.type=types.kSetDomTreeHeaderReceived;
                    dispatch(dispatchObject);
                }else if(more=='footer')
                {
                    dispatchObject.type=types.kSetDomTreeFooterReceived;
                    dispatch(dispatchObject);
                }else{
                    dispatchObject.type=types.kSetDomTreeReceived;
                    dispatch(dispatchObject);
                }
                
                // dispatch({type:types.kSetDomTreeReceived, status:status, code:code, message:message, share:share,dom:dom,newestId:newestId,lastId:lastId});
            },
            (error) => {
                dispatch({'type': types.kActionError});
            });
    }
};


